package src.graph;

import src.node.Node;
import src.edge.Edge;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.math.*;

/**
 * Created by IntelliJ IDEA.
 * User: NRG
 * Date: 02.11.12
 * Time: 11:06
 * To change this template use File | Settings | File Templates.
 */
public class Graph {
    List<Node> nodes;
    List<Edge> edges;

    public Graph() {
        nodes = new ArrayList<Node>();
        edges = new ArrayList<Edge>();
    }

    public void addNode(Node newNode) {
        nodes.add(newNode);
    }

    public void addEdge(Edge newEdge) {
        if (newEdge.getWeight() == 0)
            return;
        edges.add(newEdge);
    }

    public double getDistance(Node one, Node two) {
        if (one == two)
            return 0;

        LinkedHashMap<String, Integer> oneWords = one.getWords();
        LinkedHashMap<String, Integer> twoWords = two.getWords();
        Set<String> wordSet = oneWords.keySet();
        double distance = 0;

        //distance for file one!
        for (String x : wordSet) {
            if (twoWords.containsKey(x))
                distance += Math.pow(oneWords.get(x) - twoWords.get(x),2);
            //else
            //    distance += Math.pow(oneWords.get(x),2);
        }

        //distance for file two1
        wordSet = twoWords.keySet();
        for (String x : wordSet) {
            //if (!oneWords.containsKey(x))
            //    distance += Math.pow(twoWords.get(x),2);
        }

        return Math.sqrt(distance);
    }

    public void linkAllNodes() {
        Edge edg = null;
        double weight = 0;
        for (int i = 0; i < nodes.size(); i++) {
            for (int j = i + 1; j < nodes.size(); j++) {
                weight = getDistance(nodes.get(i), nodes.get(j));
                edg = new Edge(nodes.get(i), nodes.get(j), weight);
                addEdge(edg);
                //edges.add(edg);
            }
        }
    }

    public String edgesInfo() {
        StringBuffer sb = new StringBuffer();
        for (Edge x : edges) {
            sb.append(x + "\n");
        }
        return sb.toString();
    }

    public String nodesInfo() {
        StringBuffer sb = new StringBuffer();
        for(Node x: nodes){
            sb.append(x+"\n");
        }
        return sb.toString();
    }

}

